/**
  ******************************************************************************
  * @file           : Button.h
  * @author         : admin
  * @brief          : None
  * @attention      : None
  * @date           : 2024/10/11
  ******************************************************************************
  */

#ifndef BUTTON_H
#define BUTTON_H
#include <Arduino.h>
#define ARDUINO_RUNNING_CORE 1


typedef void (*CBFunc)(void);

class Button
{
public:
    Button(uint8_t _io);
    Button(uint8_t _io1, uint8_t _io2);
    bool isPressed(void);
    void setPressedCallback(CBFunc _cb);
    void setUnPressedCallback(CBFunc _cb);
private:
    CBFunc pressedCb;
    CBFunc unpressedCb;
    uint8_t io;
    uint8_t io1;
    uint8_t io2;
    uint8_t pinNum;
    bool prevState;

    static void taskLoop(void *param){
        Button *self = (Button *)param;
        while(1){
            bool isPressed = self->isPressed();
            if(self->prevState != isPressed){
                //Serial.printf("button change prevState=%d current=%d\n",(int)self->prevState,(int)isPressed);
                if(isPressed && self->pressedCb){
                    self->pressedCb();
                }
                if((!isPressed) && self->unpressedCb){
                    self->unpressedCb();
                }
                self->prevState = isPressed;
                //Serial.printf("button change prevState=%d\n",(int)self->prevState);
            }
            yield();
        }
    }
};
extern Button buttonA,buttonB,buttonAB;
#endif //XYXKC_ESP32_E_BUTTON_H
